const mysql = require('mysql2/promise')
const config = require('./config')

// 作者数据
const authors = [
  {
    id: 1,
    name: '天蚕土豆',
    description: '著名网络小说作家，代表作《斗破苍穹》'
  },
  {
    id: 2,
    name: '辰东',
    description: '白金级网络小说作家，代表作《完美世界》'
  },
  { id: 3, name: '叶天南', description: '都市小说作家，擅长医术题材' },
  {
    id: 4,
    name: '我吃西红柿',
    description: '起点中文网白金作家，代表作《盘龙》'
  },
  {
    id: 5,
    name: '猫腻',
    description: '网络文学界的鬼才作家，代表作《庆余年》'
  },
  {
    id: 6,
    name: '烽火戏诸侯',
    description: '历史军事小说大师，代表作《雪中悍刀行》'
  },
  { id: 7, name: '唐家三少', description: '网络小说之王，代表作《斗罗大陆》' }
]

// 小说数据
const novels = [
  {
    id: 1,
    title: '斗破苍穹',
    author: '天蚕土豆',
    author_id: 1,
    cover_url:
      'https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=300&h=400&fit=crop',
    description:
      '这里是斗气大陆，没有花俏的魔法，有的，仅仅是繁衍到巅峰的斗气！在这里，斗气就是一切！',
    category: 'fantasy',
    status: 'completed',
    word_count: 5400000,
    chapter_count: 1648,
    rating: 4.6,
    rating_count: 89234,
    view_count: 12500000,
    favorite_count: 345678,
    tags: JSON.stringify(['玄幻', '热血', '升级流', '经典']),
    is_vip: true,
    price: 299,
    last_chapter_title: '大结局：斗帝归来',
    last_chapter_time: '2023-08-20 15:30:00'
  },
  {
    id: 2,
    title: '斗罗大陆',
    author: '唐家三少',
    author_id: 7,
    cover_url:
      'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop',
    description:
      '唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。',
    category: 'fantasy',
    status: 'completed',
    word_count: 8888772,
    chapter_count: 336,
    rating: 4.8,
    rating_count: 298765,
    view_count: 45600000,
    favorite_count: 1234567,
    tags: JSON.stringify(['玄幻', '武魂', '穿越', '经典', '唐家三少']),
    is_vip: true,
    price: 399,
    last_chapter_title: '第三百三十六章 成神（大结局）',
    last_chapter_time: '2009-12-13 20:00:00'
  },
  {
    id: 3,
    title: '完美世界',
    author: '辰东',
    author_id: 2,
    cover_url:
      'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=300&h=400&fit=crop',
    description:
      '一粒尘可填海，一根草斩尽日月星辰，弹指间天翻地覆。群雄并起，万族林立，诸圣争霸，乱天动地。',
    category: 'fantasy',
    status: 'ongoing',
    word_count: 6200000,
    chapter_count: 1890,
    rating: 4.8,
    rating_count: 156789,
    view_count: 28900000,
    favorite_count: 567890,
    tags: JSON.stringify(['玄幻', '无敌流', '热血', '经典']),
    is_vip: true,
    price: 399,
    last_chapter_title: '第1890章：仙域风云',
    last_chapter_time: '2024-01-15 09:00:00'
  },
  {
    id: 4,
    title: '都市之超级医圣',
    author: '叶天南',
    author_id: 3,
    cover_url:
      'https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?w=300&h=400&fit=crop',
    description:
      '一代医圣重生都市，凭借前世的医术和修为，在都市中纵横捭阖，谱写传奇人生。',
    category: 'urban',
    status: 'ongoing',
    word_count: 3200000,
    chapter_count: 980,
    rating: 4.3,
    rating_count: 45678,
    view_count: 8900000,
    favorite_count: 234567,
    tags: JSON.stringify(['都市', '医术', '重生', '爽文']),
    is_vip: false,
    price: 0,
    last_chapter_title: '第980章：医圣威名',
    last_chapter_time: '2024-01-10 14:20:00'
  },
  {
    id: 5,
    title: '霸道总裁的小娇妻',
    author: '我吃西红柿',
    author_id: 4,
    cover_url:
      'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?w=300&h=400&fit=crop',
    description:
      '她是豪门千金，却被家族抛弃。他是商界霸主，冷酷无情却独独对她温柔...',
    category: 'romance',
    status: 'completed',
    word_count: 1800000,
    chapter_count: 567,
    rating: 4.2,
    rating_count: 78901,
    view_count: 15600000,
    favorite_count: 456789,
    tags: JSON.stringify(['都市', '总裁', '甜宠', '豪门']),
    is_vip: true,
    price: 199,
    last_chapter_title: '第567章：幸福终章',
    last_chapter_time: '2023-11-28 16:45:00'
  },
  {
    id: 6,
    title: '大明锦衣卫',
    author: '烽火戏诸侯',
    author_id: 6,
    cover_url:
      'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop',
    description:
      '大明王朝，锦衣卫横行，一个现代人穿越到明朝，成为锦衣卫中的一员...',
    category: 'historical',
    status: 'ongoing',
    word_count: 4200000,
    chapter_count: 1200,
    rating: 4.5,
    rating_count: 67890,
    view_count: 18900000,
    favorite_count: 345678,
    tags: JSON.stringify(['历史', '穿越', '明朝', '权谋']),
    is_vip: true,
    price: 299,
    last_chapter_title: '第1200章：风云再起',
    last_chapter_time: '2024-01-12 10:30:00'
  },
  {
    id: 7,
    title: '星际争霸之虫族崛起',
    author: '猫腻',
    author_id: 5,
    cover_url:
      'https://images.unsplash.com/photo-1446776877081-d282a0f896e2?w=300&h=400&fit=crop',
    description:
      '在遥远的未来，人类已经踏出地球，征服星辰大海。但虫族的威胁依然存在...',
    category: 'scifi',
    status: 'ongoing',
    word_count: 3800000,
    chapter_count: 890,
    rating: 4.4,
    rating_count: 45678,
    view_count: 9800000,
    favorite_count: 234567,
    tags: JSON.stringify(['科幻', '星际', '虫族', '未来']),
    is_vip: true,
    price: 249,
    last_chapter_title: '第890章：虫群进化',
    last_chapter_time: '2024-01-08 14:20:00'
  }
]

// 章节数据
const chapters = [
  {
    novel_id: 1,
    chapter_number: 1,
    title: '第一章：废物？',
    content:
      '萧炎，萧家最年轻的斗之气三段的天才，却在一夜之间，斗气消失，成为废人...',
    word_count: 3200,
    is_vip: false,
    price: 0
  },
  {
    novel_id: 1,
    chapter_number: 2,
    title: '第二章：退婚',
    content: '美杜莎女王驾到，萧炎面临着人生的第一个重大危机...',
    word_count: 3400,
    is_vip: false,
    price: 0
  },
  {
    novel_id: 1,
    chapter_number: 3,
    title: '第三章：神秘戒指',
    content: '古老的戒指中，隐藏着什么秘密？药老师的出现改变了一切...',
    word_count: 3600,
    is_vip: false,
    price: 0
  },

  {
    novel_id: 2,
    chapter_number: 1,
    title: '第一章：唐门暗器',
    content: '唐三，唐门外门弟子，却掌握着唐门最高机密...',
    word_count: 2800,
    is_vip: false,
    price: 0
  },
  {
    novel_id: 2,
    chapter_number: 2,
    title: '第二章：穿越异界',
    content: '醒来时，唐三发现自己来到了一个完全不同的世界...',
    word_count: 3000,
    is_vip: false,
    price: 0
  },

  {
    novel_id: 3,
    chapter_number: 1,
    title: '第一章：仙村',
    content: '大荒深处，群山万壑，一个小村庄坐落其间...',
    word_count: 3600,
    is_vip: false,
    price: 0
  },
  {
    novel_id: 3,
    chapter_number: 2,
    title: '第二章：石昊',
    content: '村中有一个小男孩，名叫石昊，天赋异禀...',
    word_count: 3800,
    is_vip: false,
    price: 0
  },

  {
    novel_id: 4,
    chapter_number: 1,
    title: '第一章：重生归来',
    content: '一代医圣重生都市，面对全新的人生...',
    word_count: 3200,
    is_vip: false,
    price: 0
  },

  {
    novel_id: 5,
    chapter_number: 1,
    title: '第一章：意外邂逅',
    content: '她是豪门千金，他是商界霸主，命运的齿轮开始转动...',
    word_count: 2900,
    is_vip: false,
    price: 0
  }
]

async function completeMigrate () {
  let connection
  try {
    connection = await mysql.createConnection({
      host: config.database.host,
      port: config.database.port,
      user: config.database.user,
      password: config.database.password,
      database: config.database.name
    })

    console.log('🚀 开始完整数据迁移...')

    // 1. 先确保authors表有数据
    console.log('\n👤 插入/更新作者数据...')
    for (const author of authors) {
      await connection.execute(
        `
        INSERT INTO authors (id, name, description) 
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE name = VALUES(name), description = VALUES(description)
      `,
        [author.id, author.name, author.description]
      )
      console.log(`✅ 作者: ${author.name}`)
    }

    // 2. 插入/更新小说数据
    console.log('\n📚 插入/更新小说数据...')
    for (const novel of novels) {
      await connection.execute(
        `
        INSERT INTO novels (
          id, title, author, author_id, cover_url, description, category, status,
          word_count, chapter_count, rating, rating_count, view_count, favorite_count,
          tags, is_vip, price, last_chapter_title, last_chapter_time
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          title = VALUES(title), author = VALUES(author), cover_url = VALUES(cover_url),
          description = VALUES(description), category = VALUES(category), 
          status = VALUES(status), word_count = VALUES(word_count),
          chapter_count = VALUES(chapter_count), rating = VALUES(rating),
          rating_count = VALUES(rating_count), view_count = VALUES(view_count),
          favorite_count = VALUES(favorite_count), tags = VALUES(tags),
          is_vip = VALUES(is_vip), price = VALUES(price),
          last_chapter_title = VALUES(last_chapter_title),
          last_chapter_time = VALUES(last_chapter_time)
      `,
        [
          novel.id,
          novel.title,
          novel.author,
          novel.author_id,
          novel.cover_url,
          novel.description,
          novel.category,
          novel.status,
          novel.word_count,
          novel.chapter_count,
          novel.rating,
          novel.rating_count,
          novel.view_count,
          novel.favorite_count,
          novel.tags,
          novel.is_vip,
          novel.price,
          novel.last_chapter_title,
          novel.last_chapter_time
        ]
      )
      console.log(`✅ 小说: ${novel.title}`)
    }

    // 3. 插入章节数据
    console.log('\n📄 插入章节数据...')
    for (const chapter of chapters) {
      await connection.execute(
        `
        INSERT INTO chapters (novel_id, chapter_number, title, content, word_count, is_vip, price)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
          title = VALUES(title), content = VALUES(content), 
          word_count = VALUES(word_count)
      `,
        [
          chapter.novel_id,
          chapter.chapter_number,
          chapter.title,
          chapter.content,
          chapter.word_count,
          chapter.is_vip,
          chapter.price
        ]
      )
      console.log(`✅ 章节: ${chapter.title}`)
    }

    // 4. 显示最终结果
    console.log('\n📊 迁移完成，检查数据...')

    const [authorCount] = await connection.execute(
      'SELECT COUNT(*) as total FROM authors'
    )
    console.log(`👤 作者总数: ${authorCount[0].total}`)

    const [novelCount] = await connection.execute(
      'SELECT COUNT(*) as total FROM novels'
    )
    console.log(`📚 小说总数: ${novelCount[0].total}`)

    const [chapterCount] = await connection.execute(
      'SELECT COUNT(*) as total FROM chapters'
    )
    console.log(`📄 章节总数: ${chapterCount[0].total}`)

    // 显示小说列表
    const [finalNovels] = await connection.execute(`
      SELECT n.id, n.title, n.author, n.category, n.status, n.rating, n.view_count, n.is_vip, n.price
      FROM novels n 
      ORDER BY n.id
    `)
    console.log('\n📋 小说列表:')
    console.table(finalNovels)

    console.log('\n🎉 完整数据迁移成功！')
  } catch (error) {
    console.error('❌ 迁移失败:', error.message)
    console.error(error)
  } finally {
    if (connection) {
      await connection.end()
    }
  }
}

completeMigrate()
